package com.dco.dcowebhook.service;

import org.springframework.beans.factory.annotation.*;
import org.springframework.mail.javamail.*;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.stereotype.Service;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.annotation.PostConstruct;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@Service
public class EmailService {

    private static final Logger logger = LoggerFactory.getLogger(EmailService.class);

    @Autowired
    private JavaMailSender mailSender;

    @Value("${SMTP_USERNAME}")
    private String senderEmail;

    @Value("${EMAIL_RECIPIENT}")
    private String recipientEmail;

    @Value("${EMAIL_SUBJECT:DCO未签署通知}")
    private String defaultSubject;

    @Value("${EMAIL_BODY:你本次提交未签署DCO}")
    private String defaultBody;

    private ExecutorService executorService;

    @PostConstruct
    public void init() {
        executorService = Executors.newSingleThreadExecutor();
    }

    /**
     * 异步发送邮件通知。
     *
     * @param subject 邮件主题
     * @param body    邮件正文
     */
    public void sendEmailAsync(String subject, String body) {
        executorService.submit(() -> sendEmail(subject, body));
    }

    /**
     * 发送邮件。
     *
     * @param subject 邮件主题
     * @param body    邮件正文
     */
    private void sendEmail(String subject, String body) {
        try {
            SimpleMailMessage message = new SimpleMailMessage();
            message.setFrom(senderEmail);
            message.setTo(recipientEmail);
            message.setSubject(subject != null ? subject : defaultSubject);
            message.setText(body != null ? body : defaultBody);

            mailSender.send(message);
            logger.info("邮件发送成功！");
        } catch (Exception e) {
            logger.error("邮件发送失败: {}", e.getMessage());
        }
    }
}
